<?php

/**
 * Description of Payment
 *
 * @author luunguyen
 * 
 * This is the model class for table "{{payment}}".
 *
 * The followings are the available columns in table '{{payment}}':
 * @property integer $id
 * @property string $payment_key
 * @property integer $payment_date
 * @property integer $method
 * @property string $type
 * @property string $name
 * @property double $amount
 * @property string $transaction_id  
 * @property integer $order_id
 * @property string $log
 *
 * The followings are the available model relations:
 * @property AuthItem $name0
 */
class Payment extends CActiveRecord
{

    const METHOD_CASH   = 1;
    const METHOD_PAYPAL = 2;
    const METHOD_VISA   = 3;
    const TYPE_APPOINT  = 'Appoint';
    const TYPE_RETAIL   = 'Retail';
    const TYPE_HOTDEAL  = 'Hotdeal';

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{payment}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('payment_date, order_id', 'required'),
            array('id, payment_date, method, order_id', 'numerical', 'integerOnly' => true),
//            array('amount', 'numerical','integerOnly' => false),
            array('payment_key', 'length', 'max' => 32),
            array('type', 'length', 'max' => 20),
            array('name', 'length', 'max' => 64),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id,transaction_id, payment_key, log, payment_date, method, type, name, amount, order_id', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'name0' => array(self::BELONGS_TO, 'AuthItem', 'name'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id'             => 'ID',
            'payment_key'    => Yii::t('main', 'Payment Key'),
            'payment_date'   => Yii::t('main', 'Payment Date'),
            'method'         => Yii::t('main', 'Method'),
            'type'           => Yii::t('main', 'Type'),
            'name'           => Yii::t('main', 'Name'),
            'amount'         => Yii::t('main', 'Amount'),
            'order_id'       => Yii::t('main', 'Order'),
            'log'            => 'Log',
            'transaction_id' => 'transaction_id'
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('payment_key', $this->payment_key, true);
        $criteria->compare('payment_date', $this->payment_date);
        $criteria->compare('method', $this->method);
        $criteria->compare('type', $this->type);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('amount', $this->amount);
        $criteria->compare('order_id', $this->order_id);
        $criteria->compare('log', $this->log);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Payment the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    function genPaymentKey()
    {
        // Prefix của ukey
        $prefix = 'PAY';

        // Chuỗi số của ukey
        $result = crc32($this->id);
        if ($result < 0)
        {
            $result = '0' . abs($result);
        }
        $key = trim(sprintf("%012d", $result));

        return "$prefix-$key";
    }

    public static function getListMethod()
    {
        return array(
            self::METHOD_CASH   => 'CASH',
            self::METHOD_PAYPAL => 'PAYPAL',
            self::METHOD_VISA   => 'VISA',
        );
    }

    public function getMethodLabel()
    {
        if (!$this->hasAttribute("method"))
            return '';

        $labelClass = 'label label-info';
        $labels     = self::getListMethod();
        $label      = isset($labels[$this->method]) ? $labels[$this->method] : $this->method;
        return "<span >$label</span>";
    }

    public function getFormatDate()
    {
        return date('D, F dS, Y', $this->payment_date);
    }

    /**
     * Get Return Data From Paypal After Payment
     * @param type $tx transaction_id
     * @return $data if success, false if payment failed
     */
    public static function getPaypalReturnData($tx)
    {
        $tx             = $_REQUEST['tx']; //transaction ID
        $identify_token = Yii::app()->params['paypal_pdt_token'];
        //Define Paypal url live or sandbox
        if (Yii::app()->params['sandbox'])
        {
            $paypal_url = 'https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_notify-synch&tx=' . $tx . "&at=$identify_token";
        }
        else
        {
            $paypal_url = 'https://www.paypal.com/cgi-bin/webscr?cmd=_notify-synch&tx=' . $tx . "&at=$identify_token";
        }

        $curl        = curl_init($paypal_url);
        $send_data   = array(
            "cmd" => "_notify-synch",
            "tx"  => $tx,
            "at"  => $identify_token
        );
        $data_string = json_encode($send_data);
        /**
         * Send to Paypal
         */
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);

        $headers  = array(
            'Content-Type: application/x-www-form-urlencoded', 'Host: www.paypal.com',
            'Connection: close');
        curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($curl);
        $lines    = explode("\n", $response);
        $data     = array();
        /**
         * Return data from Paypal
         */
        if (strcmp($lines[0], "SUCCESS") == 0)//First line is success or failed
        {
            for ($i = 1; $i < count($lines); $i++)
            {
                list($key, $val) = explode("=", $lines[$i]);

                $data[urldecode($key)] = urldecode($val);
            }
            return $data;
        }
        else
        {
            return FALSE;
        }
    }

}
